'''
@Descripttion: 
@version: 
@encoding: utf-8
@Author: qiurongcan
Date: 2025-09-08 15:58:20
LastEditTime: 2025-09-08 16:53:10
'''


# 编辑距离
"""
dp[i-1][j] -> dp[i][j] 对应的是删除操作
dp[i][j-1] -> dp[i][j] 对应的是插入操作
因为dp[i-1][j] 变到 目标字符串的次数已经明确了，现在突然增加一个元素，那就是多余的，最方便就是删除
因为dp[i][j-1] 变到 dp[i][j] 目标源字符多出来一个，所以最快的方法就是在原有的基础上插入一个字符

"""

class Solution:

    def minDistance(self, word1, word2):
        n1 = len(word1)
        n2 = len(word2)

        dp = [[0]*(n2 + 1) for _ in range(n1 + 1)]
        for j in range(1, n2 + 1):
            dp[0][j] = dp[0][j - 1] + 1

        for i in range(1, n1 + 1):
            dp[i][0] = dp[i - 1][0] + 1

        for i in range(1, n1 + 1):
            for j in range(1, n2 + 1):
                if word1[i - 1] == word2[j - 1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1

        
        return dp[-1][-1]
    

if __name__ == "__main__":

    word1 = "horse"
    word2 = "ros"

    sol = Solution()
    res = sol.minDistance(word1, word2)

    print(res)





